<template>
    <!--  有且只有一个根节点-->
    <!--  <div class="home">-->
    <!--    <img alt="Vue logo" src="../assets/logo.png">-->
    <!--    <HelloWorld msg="Welcome to Your Vue.js App"/>-->
    <!--  </div>-->
    <div>
        <el-container>
            <!--      100vh就是让左侧边栏占用整个浏览器100%的高度-->
            <el-aside :width="asideWidth" style="height: 100vh; background-color: #001529;display: flex;flex-direction: column;justify-content: space-between;">
              <div style="height: 60px;line-height: 60px; display: flex; align-items: center; justify-content: center">
                <img src="@/assets/sangulogo.png" alt="三谷LOGO" style="width: 62px; height: 40px">
                <div @click="$router.push('/')">
                  <span style="font-size: 20px; color: white" v-show="!isCollapse">三谷工具库</span>
                </div>
              </div>
                <div class="el-menu-wrapper" style="height: 90vh;overflow: auto;overflow-x: hidden">
                    <!--    关闭动画:collapse-transition="false"，default-opened让默认展开二级菜单(info信息管理)-->
                    <el-menu class="el-menu" :collapse="isCollapse" :collapse-transition="false" router background-color="#001529" text-color="rgba(255,255,255,0.65)" active-text-color="#000" style="border: none;" :default-active="$route.path">
                        <!--          只有一级菜单index属性才会生效高亮-->
                        <el-menu-item index="/home">
                            <i class="el-icon-s-home"></i>
                            <span slot="title" style="user-select: none;">系统首页</span>
                        </el-menu-item>

                        <el-submenu index="common">
                            <template slot="title">
                                <i class="el-icon-menu"></i>
                                <span style="user-select: none;">常用模块</span>
                            </template>
                            <el-menu-item index="/utils" style="user-select: none;">常用工具</el-menu-item>
                            <el-menu-item index="/bom" style="user-select: none;">Bom清单</el-menu-item>
                            <el-menu-item index="/doc" style="user-select: none;">文档管理</el-menu-item>
                            <el-menu-item index="/notice" style="user-select: none;">公告信息</el-menu-item>
                            <el-menu-item index="/website" style="user-select: none;">官网消息</el-menu-item>
                            <el-menu-item index="/distribute" style="user-select: none;">工单分发</el-menu-item>
                            <el-menu-item index="/file" style="user-select: none;">文件管理</el-menu-item>
                            <el-menu-item index="/charts" style="user-select: none;">数据统计</el-menu-item>
                        </el-submenu>

                        <el-submenu index="process">
                            <template slot="title">
                                <i class="el-icon-loading"></i>
                                <span style="user-select: none;">流程管理</span>
                            </template>
                            <el-menu-item index="/project" style="user-select: none;">研发立项</el-menu-item>
                            <el-menu-item index="/projectPro" style="user-select: none;">项目进度</el-menu-item>
                            <!-- <el-menu-item index="/utils" style="user-select: none;">销售流程</el-menu-item>
                            <el-menu-item index="/proPlan" style="user-select: none;">生产计划</el-menu-item>
                            <el-menu-item index="/notice" style="user-select: none;">零件采购</el-menu-item>
                            <el-menu-item index="/website" style="user-select: none;">精密加工</el-menu-item>
                            <el-menu-item index="/distribute" style="user-select: none;">装配调试</el-menu-item>
                            <el-menu-item index="/project" style="user-select: none;">销售发货</el-menu-item>
                            <el-menu-item index="/file" style="user-select: none;">调试售后</el-menu-item> -->
                        </el-submenu>

                        <el-submenu index="maintain">
                            <template slot="title">
                                <i class="el-icon-setting"></i>
                                <span style="user-select: none;">数据维护</span>
                            </template>
                            <el-menu-item index="/coderule" style="user-select: none;">编码字典</el-menu-item>
                            <el-menu-item index="/codelib" style="user-select: none;">历史码库</el-menu-item>
                            <el-menu-item index="/processNode" style="user-select: none;">流程节点</el-menu-item>
                            <!-- <el-menu-item index="/doc" style="user-select: none;">文档信息</el-menu-item>
                            <el-menu-item index="/notice" style="user-select: none;">公告信息</el-menu-item>
                            <el-menu-item index="/website" style="user-select: none;">官网消息</el-menu-item>
                            <el-menu-item index="/distribute" style="user-select: none;">工单分发</el-menu-item>
                            <el-menu-item index="/project" style="user-select: none;">研发立项</el-menu-item>
                            <el-menu-item index="/file" style="user-select: none;">文件管理</el-menu-item>
                            <el-menu-item index="/charts" style="user-select: none;">数据统计</el-menu-item> -->
                        </el-submenu>

                        <el-submenu index="beta">
                            <template slot="title">
                                <i class="el-icon-aim"></i>
                                <span style="user-select: none;">Beta测试</span>
                            </template>
                            <el-menu-item index="/ai" style="user-select: none;">模型训练</el-menu-item>
                            <el-menu-item index="/nas" style="user-select: none;">数据中心</el-menu-item>
                            <el-menu-item index="/sales" style="user-select: none;">销售分析</el-menu-item>
                            <el-menu-item index="/calculation" style="user-select: none;">公式计算</el-menu-item>
                        </el-submenu>

                        <!--          此处一级菜单的info没有作用，实际是子菜单在工作-->
                        <el-submenu index="info" v-if="user.role === '管理员'">
                            <template slot="title">
                                <i class="el-icon-lock"></i>
                                <span style="user-select: none;">管理员可见</span>
                            </template>
                            <el-menu-item index="/logs" style="user-select: none;">日志信息</el-menu-item>
                            <el-menu-item index="/user" style="user-select: none;">用户管理</el-menu-item>
                            <el-menu-item index="/setting" style="user-select: none;">高级设置</el-menu-item>
                            <el-menu-item index="/test" style="user-select: none;">测试页</el-menu-item>
                            <el-menu-item index="/test2" style="user-select: none;">测试页2</el-menu-item>
                            <el-menu-item index="/test3" style="user-select: none;">测试页3</el-menu-item>
                            <el-menu-item index="/test4" style="user-select: none;">测试页4</el-menu-item>
                        </el-submenu>
                    </el-menu>
                </div>

                <div style="padding: 2px;margin-bottom: 10px;">
                    <div style="display: flex;flex-direction: column;align-items: center;">
                        <div>
                            <el-image style="width: 20px; height: 20px" src="https://www.sangu.js.cn/images/gov.png"></el-image>
                        </div>
                        <div v-show="!isCollapse" style="font-size: 10px">
                          <a href="https://beian.mps.gov.cn/#/query/webSearch?code=32021402002678" style="color: #b4b0b0;text-decoration: none" target="_blank" rel="noopener noreferrer">苏公网安备32021402002678</a>
                          <br>
                          <a href="https://beian.miit.gov.cn/" style="color: #b4b0b0; text-decoration: none" target="_blank" rel="noopener noreferrer">苏ICP备2024102738-1</a>
                        </div>
                    </div>
                </div>
            </el-aside>

            <el-container>
                <!--     头部区域-->
                <el-header>
                    <!--      展开/收缩 按钮-->
                    <i :class="collapseIcon" style="font-size: 26px" @click="handleCollapse"></i>
                    <!--          <i class="el-icon-menu" style="width: 50px;"></i>-->
                    <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-left: 20px">
                        <el-breadcrumb-item :to="{path: '/'}">主页</el-breadcrumb-item>
                        <el-breadcrumb-item :to="{path: $route.path}">
                            {{$route.meta.name}}
                        </el-breadcrumb-item>
                    </el-breadcrumb>

                    <div style="flex: 1;width: 0;display: flex;align-items: center;justify-content: flex-end">
                        <i class="el-icon-chat-dot-round" style="font-size: 26px;" :class="{ 'blink': hasNewMessage }" @click="toggleMessageList"></i>
                        <div v-if="showMessageList" ref="messageList" class="message-list" style="position: absolute; top: 60px; right: 120px; width: 300px; background: white; border: 1px solid #eee; border-radius: 4px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); z-index: 100; max-height: 50vh; overflow-y: auto;">
                            <div style="padding: 10px; border-bottom: 1px solid #eee; font-weight: bold; display: flex; justify-content: space-between; align-items: center; position: sticky; top: 0; background: white; z-index: 1;">消息列表 <a href="#" style="font-weight: normal; color: #1890ff; text-decoration: none;" @click.stop="navigateToFullMsg">查看全部</a><a href="#" style="font-weight: normal; color: #ff4d4f; text-decoration: none;" @click.stop="deleteAllMessages">删除全部</a></div>
                            <div v-for="(message, index) in messages" :key="`${message.id}_${index}`" style="padding: 10px; border-bottom: 1px solid #f5f5f5; cursor: pointer; display: flex; justify-content: space-between; align-items: center;" @click="handleMessageClick(message)">
                                <div style="font-size: 14px;">{{ message.title }}</div>
                                <div style="font-size: 12px; color: #999;">{{ message.msgTime }}</div>
                                <!-- 未读状态根据消息类型显示不同颜色的点，已读状态不显示 -->
                                <div v-if="!message.isRead" :style="{
                                  'width': '8px',
                                  'height': '8px',
                                  'border-radius': '50%',
                                  'background-color': message.type === 'system' ? '#1890ff' : message.type === 'chat' ? '#52c41a' : '#ff4d4f'
                                }"></div>
                            </div>
                            <div v-if="messages.length === 0" style="padding: 10px; text-align: center; color: #999;">暂无更多</div>
                        </div>
                        <el-dropdown placement="bottom">
                            <div style="display: flex; align-items: center; cursor: default">
                                <img :src="user.avatar || 'https://img1.baidu.com/it/u=1653751609,236581088&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500'" alt="" style="width: 40px; height: 40px;border-radius: 50%;margin: 10px">
                                <span>{{user.name}}</span>
                            </div>
                            <el-dropdown-menu slot="dropdown">
                                <!-- 需要有逻辑来处理不必要的路由变化，如当前页跳当前页-->
                                <el-dropdown-item @click.native="$router.push('/person')">个人信息</el-dropdown-item>
                                <el-dropdown-item @click.native="$router.push('/pwd')">修改密码</el-dropdown-item>
                                <!--                <el-dropdown-item @click.native="$router.push('/login')">退出登录</el-dropdown-item>-->
                                <el-dropdown-item @click.native="logout">退出登录</el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                        <i class="el-icon-full-screen" style="font-size: 26px;margin-left: 10px;" @click="handleFull"></i>
                    </div>
                </el-header>

                <el-main style="height: 100vh; overflow: hidden;">
                    <!-- 新增标签页 -->
                    <el-tabs v-model="activeTab" type="card" closable @tab-remove="handleTabRemove" @tab-click="handleTabClick">
                        <el-tab-pane
                            v-for="tab in tabs"
                            :key="tab.path"
                            :label="tab.title"
                            :name="tab.path"
                        >
                        </el-tab-pane>
                    </el-tabs>
                    
                    <!-- 路由到子页面 -->
                    <div class="child-page-container" style="height: calc(100% - 40px); overflow-y: auto;">
                        <router-view :key="$route.fullPath" @update:user="updateUser" />
                    </div>
                </el-main>
            </el-container>
        </el-container>

    </div>

</template>

<script>
// @ is an alias to /src
// import HelloWorld from '@/components/HelloWorld.vue'

// export default {
//   name: 'HomeView',
//   components: {
//     HelloWorld
//   }
// }

// import axios from "axios";
import request from '@/utils/request'

export default {
    name: 'HomeView',
    data() {
        return {
            isCollapse: false, //左侧边栏默认不收缩
            asideWidth: '200px',
            collapseIcon: 'el-icon-s-fold',
            user: JSON.parse(localStorage.getItem('userInfo') || '{}'),
            tabs: [], // 存储打开的标签页
            activeTab: '', // 当前激活的标签
            cachedViews: new Set(), // 缓存已访问过的路由
            websocket: null,
            showMessageList: false, // 是否显示消息列表
            // 聊天窗口相关属性已移除，聊天功能已迁移到独立页面
            messages: [],
            reconnectCount: 0, // WebSocket重连计数
            reconnectTimer: null // 重连定时器
        }
    },  
    //请求数据
    mounted() {
        // 初始化WebSocket连接（仅在用户已登录时）
        if (this.user && this.user.token) {
            this.initNativeWebsocket();
            // 加载消息列表
            this.fetchMessages();
        }
        // 监听页面卸载事件，确保关闭WebSocket连接
        window.addEventListener('beforeunload', this.handleBeforeUnload);
    },
    beforeDestroy() {
        // 组件销毁时断开WebSocket连接
        this.closeWebSocket();
        // 移除页面卸载事件监听器
        window.removeEventListener('beforeunload', this.handleBeforeUnload);
        // 在组件销毁前移除事件监听器
        this.removeOutsideClickListener();
        // 清除重连定时器
        if (this.reconnectTimer) {
            clearTimeout(this.reconnectTimer);
            this.reconnectTimer = null;
        }
    },
    computed: {
        // 计算属性，根据消息列表中是否有未读消息决定是否闪烁
        hasNewMessage() {
            return this.messages.some(message => !message.isRead);
        }
    },
    // 共享实例给子组件
    provide(){      
        return {        
            getWebsocket: () => this.websocket      
        }
    },
    watch: {
        $route: {
            handler(route) {
                this.addTab(route)
            },
            immediate: true
        }
    },
    methods: {
        // 获取消息列表
        fetchMessages() {
            // 携带当前用户ID请求消息列表
            this.$request.get(`/messageBox/list?userId=${this.user.id}`)
                .then(res => {
                    if (res && res.data) {
                        this.messages = res.data;
                    }
                })
                .catch(error => {
                    console.error('获取消息列表失败:', error);
                    this.$message.error('获取消息列表失败，请重试');
                });
        },
        // 格式化时间
        formatTime(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}`;
        },
        
        // 滚动消息列表到顶部
        scrollToTop() {
            setTimeout(() => {
                if (this.$refs.messageList) {
                    this.$refs.messageList.scrollTop = 0;
                }
            }, 0);
        },
        // 处理页面卸载
        handleBeforeUnload() {
            this.closeWebSocket();
        },
        // 关闭WebSocket连接
        closeWebSocket() {
            if (this.websocket) {
                this.websocket.close();
                this.websocket = null;
                console.log('Manager：WebSocket连接已关闭');
            }
        },
        // 初始化WebSocket连接
        initNativeWebsocket() {
            // 避免重复创建连接
            if (this.websocket && this.websocket.readyState !== WebSocket.CLOSED) {
                return;
            }

            try {
                // 使用环境变量中的WebSocket服务器地址
                const wsUrl = `${process.env.VUE_APP_WS_URL}/ws/${this.user.id}`;
                console.log('Manager：尝试连接WebSocket:', wsUrl);
                this.websocket = new WebSocket(wsUrl);

                this.websocket.onopen = () => {
                    console.log('Manager：WebSocket连接已建立');
                    // 连接成功后重置重连计数
                    this.reconnectCount = 0;
                };

                this.websocket.onmessage = (event) => {
                    console.log('Manager：收到WebSocket消息:', event.data);
                    try {
                        const messageData = JSON.parse(event.data);
                        //刷新后会二次收到不完整的消息，可忽略
                        if(!messageData.msgTime){
                            return
                        }
                        // 判断是否是聊天消息
                        if (messageData.type === 'chat') {
                            const title = `[${messageData.from}]发来消息`
                            this.$notify({
                                title: title,
                                dangerouslyUseHTMLString: true,
                                message: messageData.content,
                                position: 'bottom-right',
                                type: 'info'
                            });
                            // 创建新消息对象
                            const newMessage = {
                                id: messageData.id || Date.now(),
                                title: title,
                                content: messageData.content,
                                msgTime: messageData.msgTime,
                                isRead: false,
                                type: messageData.type || 'chat',  // 确保包含type属性
                                fromUserId: messageData.oppo
                            };
                            // 添加到消息列表
                            this.messages.unshift(newMessage);
                            // 如果消息列表是展开的，自动滚动到顶部
                            if (this.showMessageList) {
                                this.scrollToTop();
                            }
                        } else if (messageData.type === 'init') {
                            console.log('初始化消息:', messageData);
                        } else if (messageData.type === 'system') {
                            // 处理通知类型消息
                            const newMessage = {
                                id: messageData.id || Date.now(),
                                title: messageData.title || '系统通知',
                                content: messageData.content,
                                time: messageData.msgTime,
                                isRead: false,
                                type: messageData.type || 'system'  // 确保包含type属性
                            };
                            this.messages.unshift(newMessage);
                        } else if (messageData.type === 'refresh') {
                            alert("有刷新")
                        } else if(['success', 'error', 'fail'].includes(messageData.type)){
                            // 刷新当前页面以显示最新数据
                            console.log('收到后端消息，刷新页面:', messageData.content);
                            this.$router.go(0);
                        }   else {
                            // 处理其他类型的消息
                            console.log('其他类型消息:', messageData);
                            // 为其他类型消息也创建消息对象
                            const newMessage = {
                                id: messageData.id || Date.now(),
                                title: messageData.title || '未知消息',
                                content: messageData.content,
                                msgTime: messageData.msgTime,
                                isRead: false,
                                type: messageData.type || 'unknown'  // 确保包含type属性
                            };
                            this.messages.unshift(newMessage);
                        }
                    } catch (error) {
                        console.error('解析WebSocket消息失败:', error);
                    }
                };

                this.websocket.onerror = (error) => {
                    console.error('Manager：WebSocket错误:', error);
                    // 错误发生后尝试重连
                    this.handleReconnect();
                };

                this.websocket.onclose = (event) => {
                    console.log('Manager：WebSocket连接已关闭', event);
                    // 非正常关闭时尝试重连
                    if (!event.wasClean) {
                        this.handleReconnect();
                    }
                };
            } catch (error) {
                console.error('Manager：创建WebSocket连接失败:', error);
                this.handleReconnect();
            }
        },

        // 处理重连逻辑
        handleReconnect() {
            // 限制重连次数，避免无限循环
            if (!this.reconnectCount) {
                this.reconnectCount = 0;
            }
            this.reconnectCount++;
            if (this.reconnectCount > 5) {
                console.warn('Manager：WebSocket重连次数已达上限，停止重连');
                return;
            }

            // 指数退避重连策略
            const delay = Math.min(1000 * Math.pow(2, this.reconnectCount), 30000);
            console.log(`Manager：${delay}毫秒后尝试重连WebSocket`);
            this.reconnectTimer = setTimeout(() => {
                this.initNativeWebsocket();
            }, delay);
        },
        // 添加标签页
        addTab(route) {
            if (!route.meta || !route.meta.name) return
            const existingTab = this.tabs.find(tab => tab.path === route.path)
            if (!existingTab) {
                this.tabs.push({
                    title: route.meta.name,
                    path: route.path
                })
                this.cachedViews.add(route.name)
            }
            this.activeTab = route.path
        },
        // 关闭标签页
        handleTabRemove(targetName) {
            const tabs = this.tabs
            let activeTab = this.activeTab
            
            if (activeTab === targetName) {
                tabs.forEach((tab, index) => {
                    if (tab.path === targetName) {
                        const nextTab = tabs[index + 1] || tabs[index - 1]
                        if (nextTab) {
                            activeTab = nextTab.path
                        }
                    }
                })
            }
            
            this.activeTab = activeTab
            this.tabs = tabs.filter(tab => tab.path !== targetName)
            // 所有标签关闭时跳转首页
            if (this.tabs.length === 0) {
                this.$router.push('/home')
            } else {
                this.$router.push(activeTab)
            }
        },
        
        // 点击标签页跳转
        handleTabClick(tab) {
            this.$router.push(tab.paneName)
        },
        // 用户信息更细以后通信过来更新
        updateUser(user) {
            //这里赋值是深拷贝，内存地址指向直接改变，也就是在通信发生之前子页的改变将直接影响父页的改变。
            // this.user=user
            this.user = JSON.parse(JSON.stringify(user))
        },
        logout() {
            localStorage.removeItem('userInfo')
            this.$router.push('/login')
        },
        handleCollapse() {
            this.isCollapse = !this.isCollapse
            this.asideWidth = this.isCollapse ? '70px' : '200px'
            this.collapseIcon = this.isCollapse
                ? 'el-icon-s-unfold'
                : 'el-icon-s-fold'
        },
        handleFull() {
            document.documentElement.requestFullscreen()
        },
        // 处理消息点击
        toggleMessageList() {
            this.showMessageList = !this.showMessageList;
            if (this.showMessageList) {
                // 添加点击外部区域关闭事件 - 使用防抖避免重复添加
                this.$nextTick(() => {
                    // 先移除可能存在的监听器，避免重复
                    this.removeOutsideClickListener();
                    document.addEventListener('click', this.closeMessageOutside);
                });
            } else {
                this.removeOutsideClickListener();
            }
        },
        // 移除外部点击事件监听器
        removeOutsideClickListener() {
            document.removeEventListener('click', this.closeMessageOutside);
        },
        closeMessageOutside(e) {
            const messageList = this.$refs.messageList;
            const icon = e.target.closest('.el-icon-chat-dot-round');
            
            if (!messageList) return;
            
            // 检查点击是否在消息列表内或图标上
            const clickedInsideList = messageList.contains(e.target);
            const clickedOnIcon = icon !== null;
            
            if (!clickedInsideList && !clickedOnIcon) {
                this.showMessageList = false;
                this.removeOutsideClickListener();
            }
        },
        handleMessageClick(message) {
            if (!message) return;
            try {
                // 标记消息为已读
                message.isRead = 1;
                console.log('点击了消息:', message);
                
                // 获取原始ID（去除唯一性后缀）
                const originalId = String(message.id).split('_')[0];
                
                // 向后端更新消息已读状态
                // this.updateMessageReadStatus(originalId);
                
                // 如果是聊天消息，跳转到聊天界面
                if (message.type === 'chat') {
                    // 检查当前路由，避免重复导航
                    const currentPath = this.$route.path;
                    const currentOpponentId = this.$route.query.opponentId;
                    
                    if (currentPath === '/manager/utils/WsChat' && currentOpponentId === message.oppo) {
                        // 已经在相同的聊天页面，无需跳转
                        console.log('已经在相同的聊天页面，无需跳转');
                        return;
                    }
                    
                    // 使用catch处理可能的导航重复错误
                    this.$router.push({
                        path: '/manager/utils/WsChat',
                        query: { opponentId: message.fromUserId }
                    }).catch(err => {
                        // 忽略NavigationDuplicated错误
                        if (err.name !== 'NavigationDuplicated') {
                            console.error('导航错误:', err);
                        }
                    });
                } else if(message.type === 'system') {
                    // 跳转到消息详情页面，携带完整消息对象
                    const targetPath = '/message/detail';
                    
                    // 检查当前路由，避免重复导航
                    if (this.$route.path === targetPath && 
                        this.$route.query.messageId === String(originalId)) {
                        console.log('已经在相同的消息详情页面，无需跳转');
                        return;
                    }
                    
                    // 使用catch处理可能的导航重复错误
                    this.$router.push({
                        path: targetPath,
                        query: { 
                            messageId: originalId,
                            message: JSON.stringify(message),
                            t: Date.now()
                        }
                    }).catch(err => {
                        // 忽略NavigationDuplicated错误
                        if (err.name !== 'NavigationDuplicated') {
                            console.error('导航错误:', err);
                        }
                    });
                }else{
                    this.$message.warning("消息类型未匹配")
                }
            } catch (error) {
                console.error('处理消息点击时出错:', error);
            } finally {
                // 确保消息列表关闭和监听器清理
                this.showMessageList = false;
                this.removeOutsideClickListener();
            }
        },
        // 跳转到全部消息页面
        navigateToFullMsg() {
            try {
                // 检查当前路由，避免重复导航
                if (this.$route.path === '/fullMsg') {
                    console.log('已经在全部消息页面，无需跳转');
                    return;
                }
                
                this.$router.push({ path: '/fullMsg' }).catch(err => {
                    // 忽略NavigationDuplicated错误
                    if (err.name !== 'NavigationDuplicated') {
                        console.error('导航错误:', err);
                    }
                });
            } catch (error) {
                console.error('导航到全部消息页面失败:', error);
            } finally {
                // 确保消息列表关闭和监听器清理
                this.showMessageList = false;
                this.removeOutsideClickListener();
            }
        },
        // 向后端更新消息已读状态
        updateMessageReadStatus(messageId) {
            // 发送请求到后端更新消息已读状态
            this.$request.post('/messageBox/read',{
                id: messageId
            }).then(res => {
                console.log('消息已读状态更新成功:', res.data);
                // 更新本地消息状态 - 同时检查原始ID和唯一ID
                const msg = this.messages.find(m => 
                    String(m.id).split('_')[0] === String(messageId) || m.id === messageId
                );
                if (msg) {
                    msg.isRead = true;
                    // 如果后端返回了更新后的消息数据，可以在这里同步
                    if (res.data && res.data.data) {
                        Object.assign(msg, res.data.data);
                    }
                }
            }).catch(error => {
                console.error('消息已读状态更新失败:', error);
                // 显示错误提示
                this.$message.error('更新消息已读状态失败，请重试');
                // 如果失败，将消息状态改回未读
                const msg = this.messages.find(m => 
                    String(m.id).split('_')[0] === String(messageId) || m.id === messageId
                );
                if (msg) msg.isRead = false;
            });
        },
        // 删除全部消息
        deleteAllMessages() {
            // 检查是否有消息可删除
            if (!this.messages || this.messages.length === 0) {
                this.$message.warning('没有消息可删除');
                return;
            }
            
            // 发送删除全部消息的请求
            this.$request.delete('/messageBox/deleteAll', {
                params: {
                    userId: this.user.id
                }
            }).then(res => {
                if (res.code === '200') {
                    this.$message.success('所有消息已删除');
                    // 清空本地消息列表
                    this.messages = [];
                    // 关闭消息列表
                    this.showMessageList = false;
                    this.removeOutsideClickListener();
                } else {
                    this.$message.error('删除失败：' + res.msg);
                }
            }).catch(error => {
                console.error('删除消息失败:', error);
                this.$message.error('删除消息失败，请重试');
            });
        }
    }
}
</script>

<style>
/*二级菜单 强制改黑色*/
.el-menu--inline .el-menu-item {
    background-color: #000c17 !important;
    /*纠正字体向左偏移(包括图标的24px和图标5px边距)*/
    padding-left: 49px !important;
}

/*鼠标聚焦高亮 这里是渐变色 i是非渐变色*/
.el-menu-item:hover,
.el-submenu__title:hover,
.el-submenu__title:hover i {
    color: #fff !important;
}

/*菜单背景色*/
.el-menu-item.is-active {
    /*上下左右腾出空间，防止间隙过窄*/
    /*margin: 4px;*/
    /* background-color: #1890ff !important; */
    background-color: #ffffff !important;
    /*border-radius: 15px;*/
    /*width: calc(100% - 8px);*/
    margin-left: 4px;
}

/*图标偏右改为居中：设置高亮的margin left    展开时是i   收缩时是el-tooltip */
.el-menu-item.is-active i,
.el-menu-item.is-active el-tooltip {
    margin-left: -4px;
}

/*一级菜单 和 二级菜单 限制高度*/
.el-menu-item,
.el-submenu__title {
    height: 40px !important;
    line-height: 40px !important;
}

.el-header {
    box-shadow: 2px 0 6px rgba(8, 21, 41, 0.35);
    display: flex;
    align-items: center;
}
.el-submenu .el-menu-item {
  min-width: 192px;
}

.el-menu-wrapper::-webkit-scrollbar {
  display: none; /* Chrome, Safari 和 Opera */
}

.el-menu-wrapper {
  -ms-overflow-style: none; /* IE 和 Edge */
  scrollbar-width: none; /* Firefox */
}

/* 消息通知闪烁动画 */
@keyframes blink {
    0% { opacity: 1; }
    50% { opacity: 0; }
    100% { opacity: 1; }
}
.blink {
    animation: blink 1s linear infinite;
}
</style>
